<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <a-button v-permission="permission.add" class="filter-item" type="primary" icon="plus" @click="crudCreate">新增</a-button>
    </div>
    <!-- 表单渲染 -->
    <a-row :gutter="15">
      <!--角色管理-->
      <a-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17" style="margin-bottom: 10px">
        <a-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <a-table
            size="middle"
            row-key="name"
            :columns="columns"
            :data-source="tableData"
            :pagination="ipagination"
            :loading="loading"
            :custom-row="customRow"
            @change="handleTableChange"
          >
            <span slot="action" slot-scope="text, record">
              <udOperation
                :data="record"
                :permission="permission"
                :disabled-dle="record.id === 1"
                @crudUpdate="crudUpdate"
                @crudDelete="crudDelete(record.id)"
              />
            </span>
          </a-table>
        </a-card>
      </a-col>
      <!-- 菜单授权 -->
      <a-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <a-card class="box-card" shadow="never" title="菜单分配">
          <div slot="extra" class="clearfix">
            <a-button
              v-permission="['admin','roles:edit']"
              :disabled="!showButton"
              :loading="menuLoading"
              icon="check"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</a-button>
          </div>
          <a-tree
            v-model="checkedKeys"
            checkable
            selectable
            multiple
            :load-data="onLoadData"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :expanded-keys="expandedKeys"
            :checkStrictly="checkStrictly"
          />
        </a-card>
      </a-col>
    </a-row>
    <!-- 弹窗渲染 -->
    <role-update-modal ref="updateForm" @closeModal="closeModal" />
  </div>
</template>

<script>
import ApiTree from '@/api/system/role';
import { Slime, crud } from '@/mixins/slime';
import { getMenusTree } from '@/api/system/menu';
import RoleUpdateModal from './roleUpdateModal';
import udOperation from '@crud/UD.operation';

export default {
  name: 'Role',
  components: { udOperation, RoleUpdateModal },
  mixins: [Slime],
  data() {
    return {
      menuLoading: false,
      showButton: false,
      roleId: null,
      // tree
      treeData: [],
      selectedKeys: [],
      checkedKeys: [], // 最后的值
      expandedKeys: [], // 展开值
      checkStrictly:true, // 是否父与子关联
      // table
      tableData: [
        { name: '123123', createTime: '312123' },
      ],
      columns: [
        {
          title: '名称',
          align: 'left',
          dataIndex: 'name',
        },
        {
          title: '创建日期',
          align: 'left',
          dataIndex: 'createTime',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      permission: {
        add: ['admin', 'roles:add'],
        edit: ['admin', 'roles:edit'],
        del: ['admin', 'roles:del'],
      },
    };
  },
  created() {
    crud(ApiTree);
    this.loadData();
    this.funTreeData(0);
  },
  methods: {
    // 加载表格数据
    loadData(arg) {
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      ApiTree.getAll().then((res) => {
        const tableData = res.result.records;
        this.tableData = tableData;
      });
    },
    // 点击单行
    customRow(record) {
      return {
        on: {
          // 事件点击行
          click: (event) => {
            if (record) {
              ApiTree.menuIds(record.id).then((res) => {
                console.log('treeData', this.treeData);
                this.checkedKeys = res.result;
                this.showButton = true;
                this.roleId = record.id;
              });
            }
          },
        },
      };
    },
    // tree初始化
    funTreeData(pid) {
      getMenusTree(pid, 1).then((res) => {
        const data = res.result;
        const treeData = data.map(function (item) { // 菜单结构树
          if (item.subCount > 0) {
            item = { ...item, children: [], key: item.id };
          } else {
            item = { ...item, children: null,isLeaf: true, key: item.id };
          }
          return item;
        });
        const expandedKeys = data.map(function (item) { // 菜单展开数组
          item = item.id;
          return item;
        });
        this.treeData = treeData;
        this.expandedKeys = expandedKeys;
      });
    },
    // tree点击加载下级
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.subCount <= 0) {
          resolve();
          return;
        }
        getMenusTree(treeNode.dataRef.id, 1).then((res) => {
          const data = res.result;
          const tableData = data.map(function (item) {
            if (item.subCount > 0) {
              item = { ...item, children: [], key: item.id };
            } else {
              item = { ...item, children: null, isLeaf: true, key: item.id };
            }
            return item;
          });
          treeNode.dataRef.children = tableData;
          this.treeData = [...this.treeData];
          resolve();
        });
        this.expandedKeys.push(treeNode.dataRef.id)
      });
    },
    // 保存菜单
    saveMenu() {
      console.log(this.checkedKeys)
      const that = this;
      this.menuLoading = true;
      const role = { id: this.roleId, menuIds: this.checkedKeys.checked };
      ApiTree.editMenu(role).then(() => {
        that.$message.success('保存成功');
        this.menuLoading = false;
        this.loadData();
      }).catch(err => {
        that.$message.error('保存失败');
        this.menuLoading = false;
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
  .role-span {
    font-weight: bold;color: #303133;
    font-size: 15px;
  }
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
 ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
 ::v-deep .vue-treeselect__multi-value{
    margin-bottom: 0;
  }
 ::v-deep .vue-treeselect__multi-value-item{
    border: 0;
    padding: 0;
  }
</style>
